package com.njtoyo.taxi.admin.handler.common;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.njtoyo.taxi.admin.mapper.master.entity.ActivityRewardLog;
import com.njtoyo.taxi.admin.mapper.master.entity.Coupon;
import com.njtoyo.taxi.admin.mapper.master.entity.CustomerRegionActivityRule;
import com.njtoyo.taxi.admin.mapper.master.entity.User;
import com.njtoyo.taxi.admin.mapper.master.enums.*;
import com.njtoyo.taxi.admin.mapper.master.mapper.ActivityRewardLogMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.CouponMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.CustomerRegionActivityRuleMapper;
import com.njtoyo.taxi.admin.mapper.master.mapper.UserMapper;
import com.njtoyo.taxi.admin.mongo.entity.primary.CouponMongo;
import com.njtoyo.taxi.admin.mongo.entity.secondary.AdminGiveCustomerCouponLogMongo;
import com.njtoyo.taxi.admin.mongo.repository.primary.CouponMongoRepository;
import com.njtoyo.taxi.admin.mongo.repository.secondary.AdminGiveCustomerCouponLogMongoRepository;
import com.njtoyo.taxi.admin.rest.presenter.marketing.coupon.CouponCustomerCantonPresenter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class CustomerCouponHandler {
    @Resource
    private CustomerRegionActivityRuleMapper customerRegionActivityRuleMapper;

    @Resource
    private CouponMapper couponMapper;

    @Resource
    private CouponMongoRepository couponMongoRepository;

    @Resource
    private AdminGiveCustomerCouponLogMongoRepository adminGiveCustomerCouponLogMongoRepository;

    @Resource
    private UserMapper userMapper;

    @Resource
    private ActivityRewardLogMapper activityRewardLogMapper;

    public Long sendCustomerCoupon(CustomerRegionActivityRule customerRuleByAdCode, Long customerId, Long adCode, Date startDate) {
        if (ObjectUtil.isNull(startDate)) {
            startDate = DateUtil.date();
        }
        String detailSpecification = customerRuleByAdCode.getDetailSpecification();
        JSONObject jsonObject = JSONObject.parseObject(detailSpecification);
        // 构建插入mysql数据
        Coupon couponMysql = new Coupon();
        //红包
        couponMysql.setSaleCategory(1);
        couponMysql.setCategory(CouponCategory.reduction);
        couponMysql.setScope(CouponScope.mix);
        couponMysql.setPlatform(CouponPlatform.mix);
        couponMysql.setSourceChannel(CouponSourceChannel.activity_team);
        JSONObject coupon = jsonObject.getJSONObject("coupon");
        Double value = coupon.getDoubleValue("value");
        couponMysql.setDigit(value);
        //减免
        couponMysql.setDiscountType(false);
        //折扣或者减免金额
        couponMysql.setDiscountDigit(value);
        couponMysql.setUserId(customerId);
        Long cantonId = customerRegionActivityRuleMapper.selectCantonByAdCode(adCode);
        couponMysql.setCantonId(cantonId);
        couponMysql.setCustomerRegionId(customerRuleByAdCode.getCustomerRegionId());
        couponMysql.setGrantedTimestamp(System.currentTimeMillis() / 1000);
        couponMysql.setStartedAt(startDate);
        //有效期
        Integer day = coupon.getInteger("effectiveDay");
        couponMysql.setEndedAt(DateUtil.offsetDay(startDate, day));
        // 批量插入mysql
        Integer createCount = couponMapper.insert(couponMysql);
        log.info("优惠券插入成功", createCount);

        // 构建插入mongo数据
        CouponMongo couponMongo = new CouponMongo();

        couponMongo.setCouponId(couponMysql.getId().intValue());
        couponMongo.setCategory(couponMysql.getCategory().getCode());
        couponMongo.setPlatform(couponMysql.getPlatform().getCode());
        couponMongo.setScope(couponMysql.getScope().getCode());
        couponMongo.setDiscountType(couponMysql.getDiscountType() ? 1 : 0);
        couponMongo.setDiscountDigit(couponMysql.getDiscountDigit());
        couponMongo.setLimitType(Objects.nonNull(couponMysql.getUsageCondition()) ? couponMysql.getUsageCondition().getCode() : null);
        couponMongo.setLimitDigit(Objects.isNull(couponMysql.getUsageLimit()) ? null : Double.parseDouble(couponMysql.getUsageLimit()));
        couponMongo.setCustomerId(couponMysql.getUserId().intValue());
        couponMongo.setCantonId(Convert.toInt(couponMysql.getCantonId()));
        couponMongo.setCustomerRegionId(Convert.toInt(couponMysql.getCustomerRegionId()));
        couponMongo.setHadUsed(false);

        long startAt = couponMysql.getStartedAt().getTime() / 1000;
        long endAt = couponMysql.getEndedAt().getTime() / 1000;
        couponMongo.setStartedTimestamp((int) startAt);
        couponMongo.setEndedTimestamp((int) endAt);

        couponMongo.setGrantedTimestamp(couponMysql.getGrantedTimestamp().intValue());
        couponMongo.setCreatedAt(new Date());
        couponMongo.setUpdatedAt(new Date());

        // mongo日志
        AdminGiveCustomerCouponLogMongo logMongo = new AdminGiveCustomerCouponLogMongo();
        logMongo.setCustomer_id(couponMysql.getUserId().intValue());

        // 获取乘客姓名、手机号
        User user = userMapper.selectById(couponMysql.getUserId());
        if (ObjectUtils.isNotEmpty(user)) {
            logMongo.setCustomer_name(user.getName());
            logMongo.setCustomer_mobile_number(user.getMobileNumber());
        }
        /*logMongo.setAdmin_id(adminUser.getId());
        logMongo.setAdmin_account(adminUser.getAccount());
        logMongo.setAdmin_name(adminUser.getName());
        logMongo.setAdmin_mobile_number(adminUser.getMobileNumber());*/
        logMongo.setCoupon_id(couponMysql.getId().intValue());
        logMongo.setCategory(couponMysql.getCategory().getCode());
        logMongo.setPlatform(couponMysql.getPlatform().getCode());
        logMongo.setScope(couponMysql.getScope().getCode());
        logMongo.setDiscount_type(couponMysql.getDiscountType() ? 1 : 0);
        logMongo.setDiscount_digit(couponMysql.getDiscountDigit());
        logMongo.setLimit_type(Objects.nonNull(couponMysql.getUsageCondition()) ? couponMysql.getUsageCondition().getCode() : null);
        logMongo.setLimit_digit(Objects.isNull(couponMysql.getUsageLimit()) ? null : Double.parseDouble(couponMysql.getUsageLimit()));
        logMongo.setCreated_at(couponMysql.getGrantedTimestamp().intValue());
        log.info("开始插入mongo:primary-coupon");
        // 插入mongo（primary-coupon）
        couponMongoRepository.insert(couponMongo);

        log.info("开始插入mongo:second-admin_give_customer_coupon_log");
        // 插入mongo（second-admin_give_customer_coupon_log）
        adminGiveCustomerCouponLogMongoRepository.insert(logMongo);

        log.info("乘客优惠券发放完成");

        //奖励日志
        ActivityRewardLog activityRewardLog = new ActivityRewardLog();
        activityRewardLog.setGrantedId(customerId);
        activityRewardLog.setRewardId(couponMysql.getId());
        activityRewardLog.setRewardValue(coupon.getBigDecimal("value"));
        activityRewardLog.setRewardCategory(0);
        activityRewardLog.setRefId(customerRuleByAdCode.getId());
        activityRewardLog.setActivityCategory(0);
        activityRewardLog.setCustomerRegionId(customerRuleByAdCode.getCustomerRegionId());
        activityRewardLog.setCreatedAt(new Date());
        activityRewardLogMapper.insert(activityRewardLog);
        return couponMysql.getId();
    }
}
